//回购对手方
import React from 'react';
import { connect, routerRedux } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { message, Tooltip } from 'antd';
import { AdvancedSearch, DATA_ENTRY, ModalC, PrimaryC, TableC, ExportC } from '../../../../comps';
import myStyle from '../index.less';
import currentStyle from './index.less';
import martketConfig from '../../../../comps/business/tradingMarket/config';
//组件
import RightInfo from '../shareComp/rightInfo';
import MyModal from './myModal';
import { findValueByCode, findTitleByValue } from '../../../../utils/utils';
import moment from 'moment';

let direction = [
  { value: '1', title: '融券回购' },
  { value: '2', title: '融资回购' },
];
class RepurchaseCounterparty extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedRowKeys: [], //选中的checkbox
      searchObj: {}, //查询的条件 默认查询条件
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columnsCurrent: [
        {
          title: '投资组合',
          key: 'investmentPortfo',
        },
        {
          title: '回购代码',
          key: 'repurchaseCode',
        },
        {
          title: '回购方向',
          key: 'repurchaseDirection',
        },
        {
          title: '回购起息日',
          key: 'startTime',
          type: 'date',
        },
        {
          title: '回购到期日',
          key: 'endTime',
          type: 'date',
        },
        {
          title: '回购金额',
          key: 'repurchaseMoney',
          type: 'money',
        },
        {
          title: '回购利率',
          key: 'repurchaseRate',
          type: 'rate',
        },
        {
          title: '费用',
          key: 'fee',
          type: 'money',
        },
        {
          title: '交易场所',
          key: 'tradingPlace',
        },
        {
          title: '交易对手',
          key: 'counterpartyName',
        },
        {
          title: '交易对手类型',
          key: 'counterpartyType',
        },
        {
          title: '成交编号',
          key: 'doneNo',
        },
        {
          title: '交易对手产品代码',
          key: 'counterpartyProductCode',
        },
        {
          title: '交易对手机构编码',
          key: 'counterpartyCompanyCode',
        },
        {
          title: '来源',
          key: 'originType',
        },
      ],
      isReset: false, // 是否点击重置
      type: 'add', //目前点击的是新增的状态
      visible: false, //弹窗
      count: 0, //未补充总条数
      rowData: undefined, //编辑数据
      addedThisMonth: 0, //本月新增条数
      isHistory: false, //是否是历史日期
      holdDataList: [], //持仓日期下拉
      latestholdDate: '', //最新的持仓日期
      filteredInfo: null, //筛选信息 受控
    };
  }
  componentDidMount() {
    //查询持仓日期
    this.props.dispatch({
      type: 'bondInformationM/queryHoldDataList',
      payload: {},
      callback: (data) => {
        if (data) {
          let temp = [];
          data.map((item) => {
            temp.push({
              value: item,
              title: item,
            });
          });
          //设置默认值为最新的持仓日期 其余下拉日期为历史日期
          this.AdvancedSearchRef?.props.form?.setFieldsValue({
            holdDate: data.length ? data[0] : undefined,
          });
          let obj = this.state.searchObj;
          obj.holdDate = data.length ? data[0] : undefined;
          this.setState(
            {
              holdDataList: [...temp],
              searchObj: { ...obj },
              latestholdDate: data.length ? data[0] : undefined, ////保存最新的持仓
            },
            () => {
              this.getTableData();
            },
          );
        } else {
          this.setState({ holdDataList: [] });
        }
      },
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.tenant != this.props.tenant) {
      this.getTableData();
    }
  }
  //查询
  onQuery = (e) => {
    // 判断是历史数据还是当前数据
    if (this.AdvancedSearchRef) {
      this.setState({
        isHistory: this.state.latestholdDate == this.AdvancedSearchRef.props.form.getFieldValue('holdDate') ? false : true,
      });
    }
    this.setState(
      {
        isReset: false,
        currentPage: 1,
        searchObj: e,
      },
      () => {
        this.getTableData();
      },
    );
  };
  //重置
  onClear = () => {
    this.setState({
      isReset: true,
      filteredInfo: null, //重置清除筛选条件
      originType: undefined,
    });
    //重置日期
    this.AdvancedSearchRef?.props.form?.setFieldsValue({
      holdDate: this.state.latestholdDate,
    });
    //租户也重置
    this.props.resetTenant();
  };
  //表格分页切换
  handleTableChange = (pagination, filters) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        filteredInfo: { originType: [] },
        originType: undefined,
      });
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        filteredInfo: filters,
        originType: filters?.originType?.length ? filters.originType.join(',') : undefined,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 获取表格数据
  getTableData = () => {
    const { currentPage, numInPage, searchObj, originType } = this.state;
    this.setState(
      {
        dataSource: undefined,
        columns: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'manRepurchaseCounterpartyM/queryRepurchaseCounterpartyList',
          payload: {
            ...searchObj,
            currentPage,
            numInPage,
            originType, //来源
            tenant: this.props.tenant, //点击跳转页 就是查询原租
          },
          callback: (data) => {
            if (data?.dataSource?.length) {
              data.dataSource.map((item) => {
                item.originFlag = item.originType > 1 ? false : true;
              });
            }
            if (data) {
              this.setState({
                dataSource: data.dataSource,
                total: data.pageInfo && data.pageInfo.total,
                columns: _.cloneDeep(this.state.columnsCurrent),
                count: data.count || 0,
                addedThisMonth: data.addedThisMonth || 0,
              });
            } else {
              this.setState({
                dataSource: [],
                total: 0,
                columns: [],
                count: 0,
                addedThisMonth: 0,
              });
            }
          },
        });
      },
    );
  };

  //新增
  add = () => {
    this.setState({
      visible: true,
      type: 'add',
    });
  };
  //批量确认
  confirm = () => {
    this.props.dispatch({
      type: 'manRepurchaseCounterpartyM/batchConfirm',
      payload: { data: [...this.state.selectedRowKeys] },
      callback: (data) => {
        if (data) {
          message.success('批量确认成功！');
          this.setState({ selectedRowKeys: [] });
          this.getTableData(); //刷新列表
        }
      },
    });
  };
  //点击编辑出现弹窗
  handleFn = (record) => {
    // console.log(record)
    record.timeStamp=new Date().getTime();
    this.setState({
      visible: true,
      type: 'edit',
      rowData: record,
    });
  };
  //删除onDelete
  onDelete = (id) => {
    this.props.dispatch({
      type: 'manRepurchaseCounterpartyM/deleteById',
      payload: { id },
      callback: () => {
        message.success('删除成功!');
        //删除成功 刷新列表
        this.getTableData();
      },
    });
  };
  //改变列
  handleColumns = (columns) => {
    const {
      globalM: {
        dataDictionary: { COUNTERPARTY_TYPE = [], ORIGIN_TYPE_DICT = [] },
      },
    } = this.props;
    let { filteredInfo } = this.state;
    filteredInfo = filteredInfo || {};
    if (columns && columns.length) {
      if (columns[columns.length - 1].title != '操作' && !this.state.isHistory) {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          fixed: 'right',
          operates: [
            {
              title: '编辑',
              onClick: (record, index) => {
                this.handleFn(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'isConfirm',
                      value: ['1'],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
            {
              title: '删除',
              onClick: (record) => {
                this.onDelete(record.id);
              },
              rules: {
                disabled: { relation: 'or', items: [{ key: 'originFlag', value: [true], relation: ['='] }] },
              },
            },
          ],
        });
      }
      columns &&
        columns.map((item, index) => {
          //来源
          if (item.key == 'originType') {
            item.type = 'filterCol';
            (item.filters = (ORIGIN_TYPE_DICT || []).map((item) => {
              return { text: item.value, value: item.code };
            })),
              (item.filterMultiple = true);
            (item.filteredValue = filteredInfo.originType || null),
              (item.render = (text, record) => {
                return findValueByCode(text, ORIGIN_TYPE_DICT || []);
              });
          }
          if (item.key == 'repurchaseDirection') {
            item.render = (text, record) => {
              return findTitleByValue(text, direction);
            };
          }
          if (item.key == 'counterpartyType') {
            item.render = (text, record) => {
              return findValueByCode(text, COUNTERPARTY_TYPE);
            };
          }
          if (item.key == 'tradingPlace') {
            item.render = (text, record) => {
              return findTitleByValue(text, martketConfig);
            };
          }
        });
    }
  };
  //改变勾选
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys });
  };
  //弹窗点击确认
  onOk = () => {
    let data = this.state.EditModal.getInfo();
    if (!data) return;
    data.repurchaseRate = data.repurchaseRate / 100; //回购利率 原值传递
    data.startTime = moment(data.startTime).format('YYYY-MM-DD');
    data.endTime = moment(data.endTime).format('YYYY-MM-DD');
    this.props.dispatch({
      type: 'manRepurchaseCounterpartyM/saveCounterparty',
      payload: {
        // ...this.state.rowData,
        ...data,
        id: this.state.rowData?.id,
      },
      callback: (res) => {
        if (res) {
          //新增请求后端接口时，后端根据不同情况，返回对应的msg；当返回的msg=新增成功'' 前端关闭模态框之后，并刷新列表；其他情况不进行刷新
          this.state.EditModal.reset();
          this.setState({ visible: false });
          this.getTableData();
          this.setState({ rowData: undefined });
        }
      },
    });
  };
  //弹窗点击取消
  onCancel = () => {
    this.state.EditModal.reset();
    this.setState({
      visible: false,
      rowData: undefined,
    });
  };
  //新增时跳转到对应页面
  goPage = (tabKey) => {
    sessionStorage.setItem(
      'HGBJ_pageJump',
      JSON.stringify({
        tabKey: tabKey, // 回购簿记对应tab的key值 'BankZy' → 银行间质押式回购Tab      'tradeZy' → 交易所质押式回购Tab    'tradeXy' → 交易所协议式回购Tab
      }),
    );
    this.props.dispatch(routerRedux.push('/transactions/buyBack'));
  };
  //新增弹窗
  addModal = () => {
    return (
      <div className={currentStyle.myAddCls}>
        <div>
          新增交易所协议式回购流水：
          <a
            onClick={() => {
              this.goPage('tradeXy');
            }}
          >
            交易簿记/回购簿记 交易所协议式回购Tab
            {
              <Tooltip overlayClassName={'tableTipStyle'} title={'请点击，跳转到对应页面新增流水'}>
                {' '}
                <QuestionCircleOutlined />
              </Tooltip>
            }
          </a>
        </div>
        <div>
          新增银行间质押式回购流水：
          <a
            onClick={() => {
              this.goPage('BankZy');
            }}
          >
            交易簿记/回购簿记 银行间质押式回购Tab
            {
              <Tooltip overlayClassName={'tableTipStyle'} title={'请点击，跳转到对应页面新增流水'}>
                {' '}
                <QuestionCircleOutlined />
              </Tooltip>
            }
          </a>
        </div>
      </div>
    );
  };
  render() {
    const { originType, searchObj, columns, dataSource, currentPage, total, numInPage, selectedRowKeys, visible, type } = this.state;
    const { loading } = this.props;
    this.handleColumns(columns);
    const advanceProps = [
      {
        dataIndex: 'isConfirm',
        title: '是否已确认',
        isTrueFalseJudge: true,
        type: DATA_ENTRY.SELECT,
        allowClear: true,
      },
      {
        dataIndex: 'holdDate',
        title: '持仓日期',
        type: DATA_ENTRY.SELECT,
        allowClear: false,
        dataSource: this.state.holdDataList || [],
      },
    ];
    //多选框
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: record.isConfirm === '1' || record.isSuppleInfo === '1',
      }),
    };
    return (
      <div>
        <AdvancedSearch onRef={(ref) => (this.AdvancedSearchRef = ref)} dataSource={advanceProps} onQuery={this.onQuery} onClear={this.onClear} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
          <div style={{ display: 'flex', alignContent: 'center' }}>
            {!this.state.isHistory && (
              <div>
                <PrimaryC title='新增' onClick={this.add}></PrimaryC>
              </div>
            )}
            {!this.state.isHistory && (
              <div style={{ marginLeft: '16px', marginRight: '20px' }}>
                <PrimaryC
                  title='批量确认'
                  loading={loading.effects['manRepurchaseCounterpartyM/batchConfirm'] == true}
                  onClick={this.confirm}
                  disabled={!selectedRowKeys?.length}
                ></PrimaryC>
              </div>
            )}
            <div style={{ marginRight: '20px' }}>
              <ExportC
                url={'gateway/instrument-server/counterpartyRegulation/counterpartyExport'}
                search={{ ...searchObj, tenant: this.props.tenant, originType: originType ?? '' }}
                disabled={dataSource?.length ? false : true}
              />
            </div>
          </div>
          {!this.state.isHistory && (
            <div style={{ display: 'flex' }}>
              <RightInfo redTitle={`本月新增回购交易对手${this.state.addedThisMonth}笔`}></RightInfo>
            </div>
          )}
        </div>
        <div style={{ marginTop: '16px', position: 'relative' }}>
          <TableC
            columns={columns}
            dataSource={dataSource}
            current={currentPage}
            total={total || 0}
            pageSize={numInPage}
            rowKey='id'
            scroll={{ x: 'max-content' }}
            onChange={this.handleTableChange}
            rowSelection={!this.state.isHistory ? rowSelection : undefined}
            rowClassName={(record) => {
              return record.createTs == this.state.latestholdDate && record.firstTimeMark == 'Y' ? myStyle.redCls : '';
            }}
          ></TableC>
        </div>
        <ModalC
          visible={visible}
          onOk={this.onOk}
          onCancel={this.onCancel}
          title={type == 'add' ? '新增' : '编辑'}
          width={840}
          confirmLoading={loading.effects['manRepurchaseCounterpartyM/saveCounterparty'] == true}
          destroyOnClose={false}
          maskClosable={false}
        >
          <MyModal
            type={type}
            direction={direction}
            detailData={_.cloneDeep(this.state.rowData)}
            onRef={(ref) => {
              this.state.EditModal = ref;
            }}
          />
        </ModalC>
      </div>
    );
  }
}
export default connect(({ manRepurchaseCounterpartyM, loading, globalM }) => ({ manRepurchaseCounterpartyM, loading, globalM }))(RepurchaseCounterparty);
